package cn.oms.oms.controller;

import cn.oms.oms.entity.User;
import cn.oms.oms.exception.ServiceException;
import cn.oms.oms.service.IUserService;
import cn.oms.oms.vo.UserReqVo;
import cn.oms.oms.vo.UserVo;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author AllenChen曾晨
 * @since 2022-04-29
 */
@RestController
@RequestMapping("/oms/user")
@Slf4j
public class UserController {

    @Autowired
    public IUserService userService;



    /**
     * 根据查询条件查询用户列表
     * @param userVo
     * @return
     */
    @PostMapping("/selectUserList")
    public PageInfo<User> selectUserList(UserVo userVo){
        if(userVo.getPageNum()==null||userVo.getPageNum()==0){
            userVo.setPageNum(1);
        }
        if(userVo.getPageSize()==null||userVo.getPageSize()==0){
            userVo.setPageSize(5);
        }
        log.debug("接收到信息:{}",userVo);
        PageInfo<User> pageInfo = userService.selectUserList(userVo);
        return pageInfo;
    }

    /**
     * 根据用户ID查询用户详情
     * @param userVo
     * @return
     */
    @PostMapping("/selectUserDetail")
    public User selectUserDetail(UserVo userVo){
        log.debug("接收到信息:{}",userVo);
        User user = userService.selectUserDetail(userVo);
        return user;
    }

    /**
     * 新增用户
     * @param userReqVo
     * @return
     */
    @PostMapping("/addUser")
    public String addUser(@Validated UserReqVo userReqVo, BindingResult result){
        log.debug("接收到信息:{}",userReqVo);
        if(result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        String res = userService.addUser(userReqVo);
        return res;
    }

    /**
     * 修改用户
     * @param userReqVo
     * @return
     */
    @PostMapping("/updateUser")
    public String updateUser(@Validated UserReqVo userReqVo, BindingResult result){
        log.debug("接收到信息:{}",userReqVo);
        if(result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        String res = userService.updateUser(userReqVo);
        return res;
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable Integer id){
        log.debug("接收到信息:{}",id);
        String res = userService.deleteUser(id);
        return res;
    }

}
